package org.caro.actions.message;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;


import org.caro.gui.ChatZoneArea;
import org.caro.utils.Constants;

public class ReceiveMessage extends Thread {
	private Socket socket;
	private BufferedReader bufferedReader;
	private String host;
	private int port;
	private int mode;
	private ChatZoneArea chatZone;
	public ReceiveMessage(String host, int port, int mode) {
		super("ReceiveMessage");
		this.host = host;
		this.port = port;
		this.mode = mode;
		
	}
	
	@Override
	public void run() {
		try{
			if (mode == Constants.HOST) {
				ServerSocket server = new ServerSocket(port);
				socket = server.accept();
				server.close();
			} else
				socket = new Socket(host, port);
			bufferedReader = new BufferedReader(new InputStreamReader( socket.getInputStream()));
			while(true){
				chatZone.chatByAway(bufferedReader.readLine());
			}
		}catch(Exception ex){}
	}

	public void doAction(ChatZoneArea chatZone) throws Exception {
		this.chatZone = chatZone;
		start();
	}
	
	public void closeConnection() throws Exception{
		bufferedReader.close();
		socket.close();
	}

}
